package com.example.royalchef.activity;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.widget.GridView;
import android.widget.Toast;

import com.example.royalchef.R;
import com.example.royalchef.adaper.ChildAdapter;

import java.util.ArrayList;

public class ShowImageActivity extends Activity {
    private GridView mGridView;
    private ChildAdapter adapter;
    private final static int PHOTORESULT = 2;
    private ArrayList<String> imageList;
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case PHOTORESULT:
                    adapter = new ChildAdapter(ShowImageActivity.this, imageList, mGridView);
                    mGridView.setAdapter(adapter);
                    break;
            }
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.show_image_activity);
        initView();
        initData();

    }

    private void initView() {
        mGridView = (GridView) findViewById(R.id.child_grid);
    }

    private void initData() {
        imageList = new ArrayList<>();
        getImages();
    }

    private void getImages() {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Toast.makeText(this, "没有sd", Toast.LENGTH_SHORT).show();
            return;
        }

        new Thread(new Runnable() {

            @Override
            public void run() {
                Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                ContentResolver mContentResolver = ShowImageActivity.this.getContentResolver();

                Cursor mCursor = mContentResolver.query(mImageUri, null,
                        MediaStore.Images.Media.MIME_TYPE + "=? or "
                                + MediaStore.Images.Media.MIME_TYPE + "=?",
                        new String[]{"image/jpeg", "image/png"}, MediaStore.Images.Media.DATE_MODIFIED);

                while (mCursor.moveToNext()) {
                    String path = mCursor.getString(mCursor
                            .getColumnIndex(MediaStore.Images.Media.DATA));
                    imageList.add(path);
                }

                mCursor.close();
                mHandler.sendEmptyMessage(PHOTORESULT);

            }
        }).start();
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        intent.putStringArrayListExtra("checkList", adapter.getCheckList());
        setResult(PHOTORESULT, intent);
        finish();
    }

}
